package com.gec.system.util;

import com.gec.model.pojo.TCategory;

import java.util.ArrayList;
import java.util.List;

public class TCategoryHelper {

    // 构建树结构
    public static List<TCategory> buildTree(List<TCategory> list) {
        //创建集合封装最终数据
        List<TCategory> trees = new ArrayList<>();
        //遍历参数集合
        for (TCategory tCategory : list) {
            //找到递归入口，pid = 0
            if (tCategory.getPid().equals("0")) {
                trees.add(findChildren(tCategory, list));
            }
        }
        System.out.println("树大小："+trees.size());
        return trees;
    }

    // 从根节点进行递归，查询子节点
    // 判断 id = pid 是否相同，如果相同是子节点，进行数据封装
    public static TCategory findChildren(TCategory tCategory, List<TCategory> treeNodes) {
        // 数据初始化
        tCategory.setChildren(new ArrayList<TCategory>());
        // 遍历递归查找
        for (TCategory treeNode : treeNodes) {
            if (tCategory.getId().equals(treeNode.getPid())) {
                if (tCategory.getChildren() == null) {
                    tCategory.setChildren(new ArrayList<>());
                }
                tCategory.getChildren().add(findChildren(treeNode, treeNodes));
            }
        }
        return tCategory;
    }
}
